package grimbo.goodwinfooty.server.mvc;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private UserService userService;
	private List protectedResources;
	private List<String> adminUsers;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (!protectedResources.contains(handler)) {
			return true;
		}

		User user = userService.getCurrentUser();

		if (null == user) {
			String loginUrl = userService.createLoginURL(request
					.getRequestURI());
			response.sendRedirect(loginUrl);
			return false;
		}

		if (!adminUsers.contains(user.getEmail().toLowerCase())) {
			throw new UserNotAuthorisedException(user.getEmail());
		}

		request.setAttribute("user", user);
		request.setAttribute("logoutUrl", userService.createLogoutURL("/"));

		return true;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public List getProtectedResources() {
		return protectedResources;
	}

	public void setProtectedResources(List protectedResources) {
		this.protectedResources = protectedResources;
	}

	public List<String> getAdminUsers() {
		return adminUsers;
	}

	public void setAdminUsers(List<String> adminUsers) {
		this.adminUsers = adminUsers;
	}

	class UserNotAuthorisedException extends Exception {

		public UserNotAuthorisedException() {
			super();
			// TODO Auto-generated constructor stub
		}

		public UserNotAuthorisedException(String message, Throwable cause) {
			super(message, cause);
			// TODO Auto-generated constructor stub
		}

		public UserNotAuthorisedException(String message) {
			super(message);
			// TODO Auto-generated constructor stub
		}

		public UserNotAuthorisedException(Throwable cause) {
			super(cause);
			// TODO Auto-generated constructor stub
		}

	}
}
